#include <unistd.h>
#include <string.h>
#include <sys/syscall.h>
#include <netdb.h>
#include <arpa/ip_addr.h>

#define _HOSTNAME_NR 8

struct hostent* gethostbyname(const char* name)
{
    if (!name)
    {
        return NULL;
    }

    static struct hostent s_hostent;
    static char *s_aliases[2];
    static ip_addr_t s_ipaddr[_HOSTNAME_NR];
    static ip_addr_t *s_phostent_addr[_HOSTNAME_NR];
    static char s_hostent_name[64];
    static char s_aliases_name[64];
    int i;

    s_hostent.h_name = (char*)s_hostent_name;

    /* aliases pointer array */
    s_aliases[0] = s_aliases_name;
    s_aliases[1] = NULL;
    s_hostent.h_aliases = (char **)&s_aliases;

    /* addr pointer array */
    for (i = 0; i < _HOSTNAME_NR; i++)
    {
        s_phostent_addr[i] = &s_ipaddr[i];
    }
    s_hostent.h_addr_list = (char**)&s_phostent_addr;
    
    if (syscall2(int, SYS_GETHOSTBYNAME, name, &s_hostent) != 0)
    {
        return NULL;
    }

    /* clear entry if no ipaddr */
    if (s_aliases_name[0] == '\0')
    {
        s_aliases[0] = 0;
    }
    
    for (i = 0; i < _HOSTNAME_NR; i++)
    {
        if (*(uint32_t *)&s_ipaddr[i] == 0)
        {
            s_phostent_addr[i] = 0;
        }
    }

    return &s_hostent;
}
